import React, { Component, Fragment } from "react";
// antd
import { Modal, Table, Button, Col, Pagination, Form, Input, message, Transfer, Tree } from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../utils/request';


class GroupManage extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "ID", dataIndex: "id", key: "id"},
                {title: "分组名称", dataIndex: "name", key: "name"},
                {title: "操作", dataIndex: "operation", key: "operation",
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditGroupUserBtn({rowData: rowData, status: true})}>用户</Action.Button>
                                    <Action.Button onClick={() => this.onEditGroupMenuBtn({rowData: rowData, status: true})}>菜单</Action.Button>
                                    <Action.Button onClick={() => this.onEditGroupBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                    <Action.Button onClick={() => this.onDeleteGroupBtn(rowData)}>删除</Action.Button>
                                </Action>
                            </div>

                        )
                    }           
                }
            ],
            loading: false,
            search_group_name: null,
            visible_add: false,
            visible_edit: false,
            visible_delete: false,
            visible_user: false,
            visible_menu: false,
            group_id: '',
            group_name: '',
            // 用户分组
            user_list: [],
            group_user_id_list: [],
            // 菜单分组
            menu_list: ['null'],
            group_menu_id_list: false,
        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
    }

    componentDidMount() {
        this.loadData()
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'name__contains': this.state.search_group_name,
        }

        // 获取分组列表
        http.get('/user_group', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }  

    /** 分组搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_group_name: data.name ? data.name : null,
            page: 1
        })
        this.loadData()
    }

    /** 分组添加用户按钮 */
    onEditGroupUserBtn = (data) => {
        http.get('/user_group/' + data.rowData.id).then(response => {
            this.setState({
                user_list: response.data.user_list,
                group_user_id_list: response.data.group_user_id_list,
                visible_user: true,
                group_id: data.rowData.id,
            })
        }).catch()
    }

    /** 分组切换用户Change */
    handleGroupAddUserChange = (group_user_id_list) => {
        this.setState({
            group_user_id_list
        })
    }

    /** 分组添加用户提交 */
    handleGroupAddUser = () => {
        const requestData = {
            type: 'changeGroupUser',
            group_user_id_list: this.state.group_user_id_list,
            group_id: this.state.group_id,
        }
        http.patch('/user_group/' + this.state.group_id, requestData).then(response => {
            message.success(response.data.msg)
            this.setState({
                visible_user: false,
                group_id: ''
            })
            this.loadData()
        })
    }

    /** 菜单按钮 */
    onEditGroupMenuBtn = (data) => {        
        http.get('/user_group/' + data.rowData.id).then(response=>{
            this.setState({
                menu_list: response.data.menu_list,
                group_menu_id_list: response.data.group_menu_id_list,
                visible_menu: true, 
                group_id: data.rowData.id,
            })
        }).catch() 

    }

    /** 用户选择菜单 */
    menuCheck = (checkedKeys) => {
        this.setState({
            group_menu_id_list: checkedKeys,
        })
    };

    /** 分组添加菜单提交 */
    handleGroupAddMenu = () => {
        const requestData = {
            group_menu_id_list: this.state.group_menu_id_list,
            type: 'changeGroupMenu',
        }
        http.patch('/user_group/' + this.state.group_id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_menu: false,
                group_menu_id_list: [],
                group_id: '',
            })
            this.loadData()
        }).catch()
    }

    /** 添加分组按钮 */
    onAddGroupBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 添加分组取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加分组提交 */
    onFinishAdd = (data) => {
        const requestData = {
            name: data.name,
        }
        http.post('/user_group', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 编辑分组按钮 */
    onEditGroupBtn = (data) => {
        this.setState({
            visible_edit: true,
        })

        // 获取分组列表
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'name': this.state.search_group_name,
        }

        // this.formRefEdit.current.setFieldsValue({
        //     id: data.rowData.id,
        //     name: data.rowData.name,
        // })     

        // 这个http请求是多余的，我也不知道为什么要加一层
        http.get('/user_group', {params: requestData}).then(response=>{
            this.formRefEdit.current.setFieldsValue({
                id: data.rowData.id,
                name: data.rowData.name,
            })     
        }).catch()
    }

    /** 编辑分组取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false,
        })
        this.formRefEdit.current.resetFields();
    }

    /** 编辑分组提交 */
    onFinishEdit = (data) => {
        const requestData = {
            name: data.name
        }
        http.put('/user_group/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false
            })
            this.loadData()
        }).catch()
    }

    /** 删除分组提交 */
    handleGroupDelete = () => {
        http.delete('/user_group/' + this.state.group_id).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_delete: false,
            })
            this.loadData()
        }).catch()    
    }

    /** 删除分组提交 */
    onDeleteGroupBtn = (data) => {
        this.setState({
            group_id: data.id,
            group_name: data.name,
            visible_delete: true
        })
    }

    render(){
        const { loading, dataSource, columns, page, total, visible_add, visible_edit, visible_delete, visible_user, visible_menu, group_name, user_list, group_user_id_list, group_menu_id_list, menu_list } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="分组名称" name="name">
                        <Input placeholder="请输入分组名称"  />
                    </Form.Item>
                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                <div style={myStyle1}><Button type="primary" onClick={this.onAddGroupBtn}>添加分组</Button></div>
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    scroll={{ y: 500, x: '70vw' }}
                    loading={loading}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="添加分组"
                    visible={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                    >
                        <Form.Item label="分组名称" name="name">
                            <Input ></Input>
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="编辑分组"
                    visible={visible_edit}
                    onCancel={this.onFinishEditCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                    >
                        <Form.Item label="分组ID" name="id" hidden>
                            <Input ></Input>
                        </Form.Item>
                        <Form.Item label="分组名称" name="name">
                            <Input ></Input>
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除分组"
                    visible={visible_delete}
                    onOk={this.handleGroupDelete}
                    onCancel={() => {this.setState({visible_delete: false, group_id: ''})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>确定删除分组<span style={{color: 'red'}}> {group_name}</span>? 删除后将无法恢复</p>
                </Modal>

                <Modal
                    title="变更组内用户"
                    visible={visible_user}
                    onOk={this.handleGroupAddUser}
                    onCancel={() => {this.setState({visible_user: false})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <Transfer
                        dataSource={user_list}
                        showSearch
                        filterOption={this.filterOption}
                        targetKeys={group_user_id_list}
                        onChange={this.handleGroupAddUserChange}
                        render={item => item.realname}
                        listStyle={{
                            width: 250,
                            height: 400,
                        }}
                    />
                </Modal>

                { menu_list.length && group_menu_id_list.length && (
                <Modal
                    title="变更组内菜单"
                    visible={visible_menu}
                    onOk={this.handleGroupAddMenu}
                    onCancel={() => {this.setState({visible_menu: false, group_menu_id_list: false})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <Tree
                        checkable
                        defaultExpandedKeys={group_menu_id_list}   // 默认展开数据
                        defaultCheckedKeys={group_menu_id_list}    // 默认选中菜单
                        onCheck={this.menuCheck}
                        treeData={menu_list}                     // 数据源
                        height={400}  // 虚拟滚动
                    />
                </Modal>)}
            </Fragment>
        )
    }
}
export default GroupManage;